<template>
  <div class="container">
    <Breadcrumb :items="[$t('menu.system'), $t('menu.system.department')]" />
    <a-card class="general-card">
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="add" style="margin-top: 25px">
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('searchTable.operation.create') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-table
        v-model:expandedKeys="expandedKeys"
        :columns="columns"
        :data="renderData"
        style="margin-top: 20px"
      >
        <template #optional="{ record }">
          <a-button
            v-if="record.pid != 0"
            type="text"
            size="small"
            @click="edit(record)"
          >
            <template #icon>
              <icon-edit />
            </template>
            编辑
          </a-button>
          <a-popconfirm
            :content="`此操作将永久删除(${record.name}), 是否继续?`"
            type="warning"
            @ok="delDepartment(record)"
          >
            <a-button
              v-if="record.pid != 0"
              type="text"
              size="small"
              status="danger"
            >
              <template #icon>
                <icon-delete />
              </template>
              删除
            </a-button>
          </a-popconfirm>

          <a-button @click="handleClick(record)" v-if="record.pid != 0"
            >权限</a-button
          >
          <a-modal
            v-model:visible="visible"
            @ok="handleOk(record)"
            @cancel="handleCancel"
          >
            <template #title> 修改权限 </template>
            <div>
              <a-tree
                :checkable="true"
                v-model:checked-keys="checkedKeys"
                :data="treeData"
              />
            </div>
          </a-modal>
        </template>
      </a-table>
    </a-card>
    <MenuForm
      v-model:visible="formDialogVisible"
      :form-data="formData"
      :selected="formModel.selected"
      :fetchData="fetchData"
    />
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick, onMounted } from 'vue';
  import { useI18n } from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import { PolicyRecord, PolicyParams } from '@/api/system';
  import {
    departmentInfo,
    deleteDepartment,
    treeDataDepartment,
    checkedKeysDepartment,
  } from '@/api/system';
  import { Pagination } from '@/types/global';
  import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import cloneDeep from 'lodash/cloneDeep';
  import Sortable from 'sortablejs';

  import MenuForm from './components/menu-form.vue';
  import { Message } from '@arco-design/web-vue';

  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  type Column = TableColumnData & { checked?: true };

  const generateFormModel = () => {
    return {
      selected: 'T91',
      number: '',
      name: '',
      contentType: '',
      filterType: '',
      createdTime: [],
      status: '',
    };
  };
  const generateFormAdd = () => {
    return {
      selected: '',
      name: '',
      age: undefined,
      section: '',
    };
  };
  const generateFormInfo = () => {
    return [
      {
        id: '',
        pid: '',
        name: '',
      },
    ];
  };
  const generateFormInfo2 = () => {
    return [
      {
        id: '',
        pid: '',
        title: '21',
      },
    ];
  };
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderData = ref(generateFormInfo());
  const renderData2 = ref(generateFormInfo2());
  const formModel = ref(generateFormModel());
  const formAdd = ref(generateFormAdd());
  const cloneColumns = ref<Column[]>([]);
  const showColumns = ref<Column[]>([]);

  const expandedKeys = ref([]);

  //权限
  const visible = ref(false);
  const checkedKeys = ref([]);
  const treeData = ref();
  const id = ref();
  const handleClick = async (data: any) => {
    visible.value = true;
    id.value = data.key;
    let treeId = {
      id: data.key,
    };
    console.log(treeId);
    const treeData1 = await treeDataDepartment(treeId.id);
    treeData.value = convertData3(treeData1.data);

    console.log('查询成功', treeData.value);

    selectKey(treeData.value);
  };

  const selectKey = (v) => {
    v.forEach((i) => {
      if (i.have === 1) {
        checkedKeys.value.push(i.key);
      }
      if (i.children && i.children.length !== 0) {
        selectKey(i.children);
      }
    });
  };

  const handleOk = (data: any) => {
    // let rules = [];
    let positionRules = {
      position_id: id.value,
      rules: checkedKeys.value,
    };

    checkedKeysDepartment(positionRules).then(() => {
      fetchData();
      Message.success('添加权限成功');
    });
    visible.value = false;
    checkedKeys.value = [];
    positionRules = <any>{};
  };
  const handleCancel = () => {
    visible.value = false;
    checkedKeys.value = [];
  };

  //编辑添加按钮
  const formData = ref();
  // console.log(formData);
  // 弹出框标记
  const formDialogVisible = ref(false);
  const add = () => {
    formData.value = {};
    formDialogVisible.value = true;
  };
  const edit = (e: any) => {
    formDialogVisible.value = true;

    formData.value = { ...e };
  };

  const size = ref<SizeProps>('medium');

  const basePagination: Pagination = {
    current: 1,
    pageSize: 20,
  };
  const pagination = reactive({
    ...basePagination,
  });
  const densityList = computed(() => [
    {
      name: t('searchTable.size.mini'),
      value: 'mini',
    },
    {
      name: t('searchTable.size.small'),
      value: 'small',
    },
    {
      name: t('searchTable.size.medium'),
      value: 'medium',
    },
    {
      name: t('searchTable.size.large'),
      value: 'large',
    },
  ]);
  const columns = [
    {
      title: t('searchTable.columns.index'),
      dataIndex: 'id',
      align: 'center',
    },
    {
      title: '部门名称',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '操作',
      slotName: 'optional',
      align: 'center',
    },
  ];
  const contentTypeOptions = computed<SelectOptionData[]>(() => [
    {
      label: t('searchTable.form.contentType.img'),
      value: 'img',
    },
    {
      label: t('searchTable.form.contentType.horizontalVideo'),
      value: 'horizontalVideo',
    },
    {
      label: t('searchTable.form.contentType.verticalVideo'),
      value: 'verticalVideo',
    },
  ]);
  const filterTypeOptions = computed<SelectOptionData[]>(() => [
    {
      label: t('searchTable.form.filterType.artificial'),
      value: 'artificial',
    },
    {
      label: t('searchTable.form.filterType.rules'),
      value: 'rules',
    },
  ]);
  const statusOptions = computed<SelectOptionData[]>(() => [
    {
      label: t('searchTable.form.status.online'),
      value: 'online',
    },
    {
      label: t('searchTable.form.status.offline'),
      value: 'offline',
    },
  ]);
  const fetchData = async (
    params: PolicyParams = { current: 1, pageSize: 20 }
  ) => {
    setLoading(true);
    try {
      // console.log(params);
      const { data } = await departmentInfo();
      // console.log(data);
      renderData.value = convertData(data);

      renderData2.value = convertData2(data);
      pagination.current = 1;
      pagination.total = 20;
    } catch (err) {
      // you can report use errorHandler or other
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  function convertData(menuList: any) {
    return menuList?.map((item) => {
      const { id, pid, name } = item;
      const son = item.son ?? [];
      const isChild = son != null && son.length !== 0;
      const currentArray: any = {
        key: id,
        pid: pid,
        name: name,
        children: [],
      };
      // 是否有子菜单，并递归处理
      if (isChild) {
        currentArray.children = convertData(son);
      }
      return currentArray;
    });
  }
  function convertData2(menuList: any) {
    return menuList?.map((item) => {
      const { id, pid, name } = item;
      const son = item.son ?? [];
      const isChild = son != null && son.length !== 0;
      const currentArray: any = {
        key: id,
        pid: pid,
        title: name,
        children: [],
      };
      // 是否有子菜单，并递归处理
      if (isChild) {
        currentArray.children = convertData2(son);
      }

      return currentArray;
    });
  }
  function convertData3(menuList: any) {
    return menuList?.map((item) => {
      const { id, pid, have, title } = item;
      const son = item.son ?? [];
      const isChild = son != null && son.length !== 0;
      const currentArray: any = {
        key: id,
        pid: pid,
        have: have,
        title: title,
        children: [],
      };
      // 是否有子菜单，并递归处理
      if (isChild) {
        currentArray.children = convertData3(son);
      }
      return currentArray;
    });
  }

  const search = () => {
    fetchData({
      ...basePagination,
      ...formModel.value,
    } as unknown as PolicyParams);
  };
  const onPageChange = (current: number) => {
    fetchData({ ...basePagination, current });
  };

  fetchData();

  const reset = () => {
    formModel.value = generateFormModel();
  };

  const delDepartment = async (data: any) => {
    console.log(data);
    let deldata = {
      id: data.key,
    };
    console.log(deldata);

    await deleteDepartment(deldata).then((res) => {
      fetchData();

      Message.success('删除成功');
    });
  };

  function fmenu(menuList: any) {
    return menuList?.map((item) => {
      const { id, pid, cat_name } = item;

      console.log(item.cat_name);
      const son = item.son ?? [];
      const isChild = son != null && son.length !== 0;
      const currentArray: any = {
        key: id,
        title: cat_name,
        children: [],
      };

      if (isChild) {
        currentArray.children = fmenu(son);
      }
      return currentArray;
    });
  }
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }
  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }
  .setting {
    display: flex;
    align-items: center;
    width: 200px;
    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
</style>
